package com.zds.support.base

import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.annotation.UiThread
import androidx.fragment.app.Fragment
import com.zds.support.R
import com.zds.support.dialog.CommonDialog
import com.zds.support.util.FastClickUtils
import com.zds.support.util.LogUtils

import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

/**
 *
 *@Description
 *@Author zc
 *@Version V1.0
 **/
abstract class SupportBaseFragment : Fragment(), View.OnClickListener, EasyPermissions.PermissionCallbacks {
    private var isViewOK = false //是否完成 View 初始化
    private var isInitView = false
    private var isFirstLoad = true //是否为第一次加载
    public val fragmentId by lazy { View.generateViewId(); }
    protected val mLoadingDialog: Dialog by lazy { getLoadingDialog() };
    protected val mActivity: Activity by lazy { requireActivity() }
    protected val mOnClickListener by lazy { this }
    protected var mToast: Toast? = null
    private var progressDialogMsg = ""
    protected var pageSize = 20
    protected val singleDialog: CommonDialog by lazy {
        CommonDialog.Builder(mActivity)
                .setSingleButtonText(R.string.confirm)
                .setOnClickListener { dialog, isPositive -> dialog.dismiss() }
                .create()
    }
    private val TAG = "SupportBaseFragment"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LogUtils.d(TAG, "${javaClass.simpleName} -> onCreate")
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        LogUtils.d(TAG, "${javaClass.simpleName} -> onCreateView")
        val view = getContentView(inflater, container, savedInstanceState);
        // 完成 initView 后改变view的初始化状态为完成
        isViewOK = true
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        LogUtils.d(TAG, "${javaClass.simpleName} -> onViewCreated")
        if (!isInitView) {
            isInitView = true
            try {
                initView()
                initDta()
            } catch (e: Exception) {

            }

        }
    }

    override fun onDestroyView() {
        isFirstLoad = false;
        super.onDestroyView()
    }


    abstract fun getContentView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View

    /**
     * fragment 初始化 view 的方法
     */
    abstract fun initView()

    /**
     * 数据初始化
     */
    abstract fun initDta()

    override fun onResume() {
        super.onResume()
        LogUtils.d(TAG, "${javaClass.simpleName} -> onResume")
        //在 onResume 进行数据懒加载
        initLoadData()
    }

    private fun initLoadData() {
        if (isViewOK && isFirstLoad) {
            //加载数据时判断是否完成view的初始化，以及是不是第一次加载此数据
            LogUtils.d(TAG, "${javaClass.simpleName} -> lazyLoadData")
            lazyLoadData()
            //加载第一次数据后改变状态，后续不再重复加载
            isFirstLoad = false
        }
    }

    /**
     * fragment 实现懒加载的方法，即在这里加载数据
     */
    abstract fun lazyLoadData()

    open fun getLoadingDialog(): Dialog {
        return Dialog(requireContext())
    }

    fun setViewsClickListener(vararg views: View) {
        for (view in views) {
            try {
                view.setOnClickListener(mOnClickListener)
            } catch (e: Exception) {
            }
        }
    }

    open fun toast(msg: String, duration: Int) {
        try {
            mToast = Toast.makeText(mActivity, msg, duration)
            mToast?.setGravity(Gravity.CENTER, 0, 0)
            mToast?.show()
        } catch (e: Exception) {

        }
    }

    fun toast(msg: String) {
        toast(msg, Toast.LENGTH_SHORT)
    }

    fun toast(@StringRes textResId: Int) {
        toast(textResId, Toast.LENGTH_SHORT)
    }

    open fun toast(@StringRes textResId: Int, duration: Int) {
        toast(getString(textResId), duration)
    }

    @UiThread
    fun showProgressDialog(msg: String) {
        progressDialogMsg = msg
        showProgressDialog(msg, true)
    }

    @UiThread
    fun showProgressDialog(@StringRes msgId: Int) {
        progressDialogMsg = getString(msgId)
        showProgressDialog(msgId, true)
    }

    @UiThread
    fun dismissProgressDialog() {
        try {
            if (mLoadingDialog.isShowing) {
                mLoadingDialog.dismiss()
            }
        } catch (e: Exception) {

        }

    }

    @UiThread
    fun setProgressDialogMsg(msg: String) {
        try {
            if (!TextUtils.equals(msg, progressDialogMsg)) {
                progressDialogMsg = msg
                mLoadingDialog.setTitle(msg)
            }

        } catch (e: Exception) {

        }
    }

    @UiThread
    fun setProgressDialogMsg(@StringRes msgRes: Int) {
        try {
            val msg = getString(msgRes)
            setProgressDialogMsg(msg)
        } catch (e: Exception) {

        }
    }

    @UiThread
    fun showProgressDialog(msg: String, cancelable: Boolean) {
        try {
            mLoadingDialog.setTitle(msg)
            mLoadingDialog.setCanceledOnTouchOutside(cancelable)
            mLoadingDialog.show()
        } catch (e: Exception) {

        }


    }

    @UiThread
    fun showProgressDialog(@StringRes msgId: Int, cancelable: Boolean) {
        showProgressDialog(getString(msgId), cancelable)
    }

    @UiThread
    fun showSingleDialog(msg: String) {
        showSingleDialog("", msg)
    }

    @UiThread
    fun showSingleDialog(@StringRes msgRes: Int) {
        showSingleDialog("", getString(msgRes))
    }

    @UiThread
    fun showSingleDialog(@StringRes titleRes: Int, @StringRes msgRes: Int) {
        showSingleDialog(getString(titleRes), getString(msgRes))

    }

    @UiThread
    fun showSingleDialog(@StringRes titleRes: Int, @StringRes msgRes: Int,
                         onClickListener: (dialog: DialogInterface, isPositive: Boolean) -> Unit) {
        showSingleDialog(getString(titleRes), getString(msgRes), onClickListener)

    }

    @UiThread
    fun showSingleDialog(title: String, msg: String) {
        showSingleDialog(title, msg, { dialog, isPositive -> })
    }

    @UiThread
    open fun showSingleDialog(title: String, msg: String,
                              onClickListener: (dialog: DialogInterface, isPositive: Boolean) -> Unit) {
        try {
            singleDialog.show()
            singleDialog.setTitle(title)
            singleDialog.setMessage(msg)
            singleDialog.setOnClickListener(onClickListener)
        } catch (e: Exception) {

        }
    }

    @UiThread
    fun showSingleDialog(@StringRes titleRes: Int, msg: String) {
        showSingleDialog(getString(titleRes), msg)
    }

    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<out String>,
                                            grantResults: IntArray) {
        // super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //将请求结果传递EasyPermission库处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {

    }

    open fun onViewClick(v: View) {

    }

    final override fun onClick(v: View?) {
        if (v != null && !FastClickUtils.isFastClick()) {
            onViewClick(v)
        }
    }
}